package controller

import (
	"encoding/json"
	"errors"
	"gadmin/model"
	"gadmin/service"

	"github.com/gin-gonic/gin"
)

func GetWorkflow(c *gin.Context) {
	uuid := c.Query("id")
	if uuid == "" {
		workflows, err := service.GetWorkflow()
		if err != nil {
			SendError(c, err)
			return
		}
		SendData(c, workflows)
	} else {
		workflows, err := service.FindWorkflow(uuid)
		if err != nil {
			SendError(c, err)
			return
		}
		SendData(c, workflows)
	}
}

func CreateOrUpdateWorkflow(c *gin.Context) {
	rawData, err := c.GetRawData()
	if err != nil {
		SendError(c, err)
		return
	}

	dataMap := make(map[string]string)
	err = json.Unmarshal(rawData, &dataMap)
	if err != nil {
		SendError(c, err)
		return
	}

	var definitionStr string
	var ok bool
	if definitionStr, ok = dataMap["definition"]; !ok {
		SendError(c, errors.New("定义请求必须包含definition参数"))
		return
	}

	_, err = service.ParseDefinition(definitionStr)
	if err != nil {
		SendError(c, err)
		return
	}

	var uuidString string
	if uuidString, ok = dataMap["uuid"]; ok {
		// 更新
		err = service.UpdateWorkflow(uuidString, definitionStr)
		if err != nil {
			SendError(c, err)
			return
		}
	} else {
		// 创建
		err = service.CreateWorkflow(definitionStr)
		if err != nil {
			SendError(c, err)
			return
		}
	}
	SendData(c, nil)
}

type RunParam struct {
	ID     uint              `json:"id"`
	Sync   bool              `json:"sync"`
	Name   string            `json:"name"`
	Inputs map[string]string `json:"inputs"`
}

func RunWorkflow(c *gin.Context) {
	var runParam RunParam

	if err := c.BindJSON(&runParam); err != nil {
		SendError(c, err)
		return
	}

	if runParam.Sync {
		var err error
		var data interface{}
		if runParam.ID != 0 {
			_, data, err = service.RunWorker(runParam.ID, runParam.Inputs, runParam.Sync)
		} else {
			_, data, err = service.RunWorkerWithName(runParam.Name, runParam.Inputs, runParam.Sync)
		}
		if err != nil {
			SendError(c, err)
			return
		}
		SendData(c, data)
	} else {
		var err error
		var workflowHistory *model.WorkflowHistory
		if err == nil {
			workflowHistory, _, err = service.RunWorker(runParam.ID, runParam.Inputs, runParam.Sync)
		} else {
			workflowHistory, _, err = service.RunWorkerWithName(runParam.Name, runParam.Inputs, runParam.Sync)
		}

		if err != nil {
			SendError(c, err)
			return
		}
		SendData(c, workflowHistory)
	}

}

func GetWorkflowHistory(c *gin.Context) {
	workflow_id := c.Query("workflow_id")
	history_id := c.Query("history_id")

	if len(workflow_id) != 0 {
		workflowHistories, err := service.GetWorkflowHistoryByWorkflowId(workflow_id)
		if err != nil {
			SendError(c, err)
			return
		}
		SendData(c, workflowHistories)
		return
	}

	if len(history_id) != 0 {
		workflowHistory, err := service.GetWorkflowHistoryByHistoryId(history_id)
		if err != nil {
			SendError(c, err)
			return
		}
		SendData(c, workflowHistory)
		return
	}

	SendError(c, errors.New("参数错误"))
}
